<template>
  <div class="cms-upload-con">
    <div v-if="!data.imgUrl" class="cms-upload-con-img ui-pt-10">
      <label
        :for="data.myId"
        class="UploadBox"
      />
    </div>
    <input
      v-if="showInput"
      :id="data.myId"
      ref="inputer"
      type="file"
      name="file"
      :disabled="disabled"
      @change="handleFileChange"
      @touchstart="handleFileChange"
    >
    <div v-if="data.imgUrl" style="position: relative; min-height: 60px;">
      <div class="UploadImgBox">
        <img :src="data.imgUrl">
        <div v-zoom class="UploadImgBox-icon el-icon-view" @click="imageZoom" />
        <div class="UploadImgBox-icon el-icon-close" @click="handleClose" />
        <label :for="data.myId" class="ChangImg" />
      </div>
      <!-- <el-tag
        class="UploadImgBox"
        disable-transitions
        :closable="!disabled"
        @close="handleClose"
      >
        <img :src="data.imgUrl">
        <label :for="data.myId" class="ChangImg" />
      </el-tag> -->
    </div>
    <div v-show="data.text" class="labelClass-title remark">{{ data.text }}</div>

  </div>
</template>
<script>
/**
 * @file 图片上传 组件
 *
 *
 * 调用：
 * 传入数据：
 * html：<upload :data="imgData" />
 *
 * 传入数据：
 * data: {
 *   myId: Math.random(),     // 组件唯一id
 *   path: 'tagIcon',         // 图片分类名称
 *   imgUrl: '',              // 图片外网名称（用于传递至后台）
 *   ImgSize: 80,             // 图片大小限制
 *   ratio: [708, 180],              // 宽 / 高
 *   text: '活动主图，建议上传228*156，大小不得超过80K的图片',          // 图片备注
 * },
 */

import { uploadFile } from 'api/common'

export default {
  props: {
    data: {
      type: Object,
      default: () => {},
      required: true
    },
    disabled: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      showInput: true,
      form: {
        file: null,
        path: 'home'
      }
    }
  },
  watch: {},
  created() {
  },
  methods: {
    // 删除图片
    handleClose() {
      this.data.imgUrl = ''
      this.data.zebUrl = ''
      this.$emit('removeImg')
    },

    imageZoom(e) {
      e.target.src = this.data.imgUrl
    },
    /**
     * 取小数
     */
    handleNum(val, n) {
      const x = 10 * n
      return Math.floor(val * x) / x
    },
    // 图片上传
    handleFileChange() {
      const inputDOM = this.$refs.inputer
      const file = inputDOM.files[0]
      this.getImageWidthAndHeight(file).then((imgInfo) => {
        if (this.data.path) this.form.path = this.data.path
        if (this.data.fileSize) this.data.fileSize = file.size
        const isLt2M = file.size / 1024 < this.data.ImgSize + 1
        if (this.data.ImgSize && !isLt2M) {
          this.$message(`请上传图片大小不超过${this.data.ImgSize}K的图片！`)
          // 利用以下这段代码重新触发组件的生命周期，解决了当重复上传同一张图片大于限制大小时，第二次上传不会出现提示的问题
          this.showInput = false
          this.$nextTick(() => {
            this.showInput = true
          })
          return
        }
        // 图片格式
        const isImg = file.type.startsWith('image')
        // const isGIF = file.type === 'image/gif'
        // const isBMP = file.type === 'image/bmp'
        if (!isImg) {
          this.$message('图片的格式必须为图片格式！')
          this.showInput = false
          this.$nextTick(() => {
            this.showInput = true
          })
          return
        }
        const formData = new window.FormData()
        Object.keys(this.form).forEach((y) => {
          formData.append(y, this.form[y])
        })
        formData.append('file', file)
        uploadFile(formData).then((re) => {
          // 改版 => 默认传相对路径
          this.data.imgUrl = re.data + '&download=false'
          this.$emit('success')
        })
        this.$refs.inputer.value = ''
      }).catch((err) => {
        console.log('err', err)
      })
    },

    // 获取上传图片宽高
    getImageWidthAndHeight(file) {
      return new Promise((resolve, reject) => {
        const imageType = /image.*/
        if (file.type.match(imageType)) {
          const reader = new window.FileReader()
          reader.onload = () => {
            const image = new window.Image()
            image.src = reader.result
            image.onload = () => {
              const sizeInfo = {}
              sizeInfo.width = image.width
              sizeInfo.height = image.height
              resolve(sizeInfo)
            }
          }
          reader.readAsDataURL(file)
        } else if (file.type.includes('video')) {
          resolve({
            width: '',
            height: ''
          })
        } else {
          reject()
        }
      })
    }
  }
}
</script>
<style lang="scss" scoped>
  .cms-upload-con{
    display: inline-block;
    min-width: 100px;
    // min-height: 100px;
    position: relative;
    margin-right: 20px;
    &-img{
      min-height: 50px;
    }
    .remark{
      line-height: 1.3;
      min-height: 20px;
      font-size: 12px;
      color: rgba(0,0,0,.6);
      padding-top: 2px;
    }
    .UploadBox{
      display: block;
      width: 50px;
      min-height: 50px;
      border: 1px dashed #d9d9d9;
      position: absolute;
      border-radius: 6px;
      cursor: pointer;
      background-image: url('../../assets/common/addImg.png');
      background-position: center;
      background-repeat: no-repeat;
      background-size: 40%;
      &:hover{
        border: 1px dashed #409EFF;
      }
    }
    input{
      position: absolute;
      // left: -999px;
      visibility: hidden;
      // width: 100%;
      // height: 100%;
    }
    .el-tag{
      background-color: #ffffff;
      border: none;
      height: 100px;
      max-width: 200px;
    }
    .UploadImgBox{
      height: 100px;
      max-width: 200px;
      position: relative;
      top: 0;
      left: 0;
      cursor: pointer;
      img{
        max-width: 80%;
        max-height: 100%;
      }
      &-icon{
        position: relative;
        z-index: 3;
        color: #606266;
        &:hover{
          color: #409EFF;
        }
      }
      .ChangImg{
        position: absolute;
        top: 0;
        left: 0;
        display: block;
        width: 100%;
        height: 100%;
        cursor: pointer;
      }
    }
    @media screen and (max-width: 480px) {
      .myUploadBox{
        .UploadImgBox{
          &.UploadImgBox5{
            width: 240px;
            height: 80px;
          }
        }
      }
    }
  }

</style>
